<template>
  <div v-loading="loading" class="container" element-loading-text="加载中...">
    <div class="app-container">
      <div class="left" element-loading-text="加载中...">
        <!-- change事件是离开input框之后的触发 input是只要内容变化就触发 -->
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="handleInput" />
        <!-- 树形组件 -->
        <!-- 高亮当前节点 -->
        <el-tree
          ref="tree"
          :data="treeData"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="handleDepartment"
        />
      </div>
      <div class="right">
        <!-- 顶部 button按钮 -->
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.replace('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="ImportEmployee">excel导入</el-button>
          <!-- <el-button size="mini" @click="ExportEmployee">excel导出</el-button> -->
          <el-popover v-model="visible" placement="left">
            <p>您确定需要excel导出吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="ExportEmployee">确定</el-button>
            </div>
            <el-button slot="reference" size="mini" style="margin-left:10px">excel导出</el-button>
          </el-popover>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableList">
          <!-- 头像 -->
          <el-table-column align="center" label="头像">
            <template #default="{ row }">
              <!-- 不是所有用户都有头像的，当用户没有头像时要显示用户名的第一个字 charAt方法 -->
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.replace(`/employee/detail/${row.id}`)">查看</el-button>
              <!-- 项目分为部门 角色 员工 员工扮演部门中的不同角色 -->
              <el-button size="mini" type="text" @click="$router.replace(`/employee/assign/${row.id}`)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="Del(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            :total="total"
            :current-page.sync="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total,prev, pager, next"
            @current-change="handlePage"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel ref="importexcel" @uploadSuccess="GetEmployeeList" />
  </div>
</template>

<script>
import { getDepartment } from '@/api/department.js'
import { getEmployeeList, exportEmployee, delEmployee } from '@/api/employee.js'
import ImportExcel from './components/import-excel.vue'
import { transListToTreeData } from '@/utils/index.js'
import FileSaver from 'file-saver'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      visible: false,
      Timer: null, // 定时器
      loading: false, // 加载
      total: null, // 总条数
      tableList: [], // 表格数组
      treeData: [], // 左侧侧边栏处理后的数据
      defaultProps: {
        label: 'name', // 显示的字段名
        children: 'children' // 子节点的字段名
      },
      // 存储查询参数
      queryParams: {
        page: 1, // 当前页码数
        pagesize: 10, // 当前页面需要的数据条数
        keyword: '', // 根据名字模糊查询
        departmentId: null// 部门id
      }
    }
  },
  created() {
    this.GetDepartment()
  },
  methods: {
    // 初始化函数 左侧tree树
    async GetDepartment() {
      this.loading = true
      const data = await getDepartment()
      this.treeData = transListToTreeData(data, 0) // 处理得到的数据
      this.queryParams.departmentId = this.treeData[0].id // 记录首个节点
      // setCurrentKey 是elementui中tree的方法
      this.$nextTick(() => { this.$refs['tree'].setCurrentKey(this.queryParams.departmentId) }) // 在页面初始化结束后 选中首节点
      // 默认初始化时先获取一次员工列表
      this.GetEmployeeList()
    },
    // 切换选择的部门
    handleDepartment(value) {
      this.queryParams.departmentId = value.id // 切换部门后 将点击的部门id赋值 向后台拉数据
      this.queryParams.page = 1 // 部门的切换 页码设置为1
      this.GetEmployeeList()
    },
    // 获取员工列表
    async GetEmployeeList() {
      this.loading = true
      const res = await getEmployeeList(this.queryParams)
      const { rows, total } = res
      this.tableList = rows // 表格数组
      this.total = total // 总条数
      this.loading = false
    },
    // 切换页面时触发
    handlePage(value) {
      this.queryParams.page = value // 新页面
      this.GetEmployeeList()
    },
    // 当input内容变化后触发 防抖处理(搜索框)
    handleInput() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.Timer)
      this.Timer = setTimeout(() => {
        this.queryParams.page = 1
        this.GetEmployeeList()
      }, 1000)
    },
    // 批量导出员工excel
    async ExportEmployee() {
      const res = await exportEmployee()
      // console.log(result) // 使用一个npm包 直接将blob文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    // 导入excel
    ImportEmployee() {
      this.$refs.importexcel.showExcelDialog = true
    },
    // 确定删除员工
    async Del(id) {
      await delEmployee(id)
      if (this.tableList.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.GetEmployeeList() // 当前页面刷新
      this.$message.success({ message: '删除员工成功', duration: 1500 })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
